from PIL import Image, ImageDraw

def draw_points_and_connect(image_path, output_path):
    # 定义点集
    points = [
        {"x": 54, "y": 107, "z": 110, "code": 0xA0, "name": "A0"},
        {"x": 59, "y": 239, "z": 110, "code": 0xA1, "name": "A1"},
        {"x": 207, "y": 242, "z": 110, "code": 0xA2, "name": "A2"},
        {"x": 336, "y": 246, "z": 110, "code": 0xA3, "name": "A3"},
        {"x": 336, "y": 110, "z": 110, "code": 0xA4, "name": "A4"},
        {"x": 336, "y": 38, "z": 110, "code": 0xA5, "name": "A5"},
        {"x": 185, "y": 101, "z": 110, "code": 0xA6, "name": "A6"}
    ]
    
    # 创建新图像（白色背景）
    width = 400
    height = 300
    image = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(image)

    for i in range(len(points)):
        points[i]["y"] = height - points[i]["y"]
    # 绘制连接线（红色）
    for i in range(len(points)):
        start_point = (points[i]["x"], points[i]["y"])
        end_point = (points[(i+1)%len(points)]["x"], points[(i+1)%len(points)]["y"])
        draw.line([start_point, end_point], fill="red", width=2)
    
    # 绘制点并标注（蓝色点和黑色文字）
    for point in points:
        x, y = point["x"], point["y"]
        # 绘制点
        draw.ellipse([(x-3, y-3), (x+3, y+3)], fill="blue")
        # 标注点名称和坐标
        text = f"{point['name']}({x},{y})"
        draw.text((x+5, y-10), text, fill="black")
    
    # 保存图像
    image.save(output_path)
    print(f"图像已保存到: {output_path}")

# 使用示例
draw_points_and_connect("background.png", "output.png")